
import requests
import base64
import re
from fontTools.ttLib import TTFont
import io
#pip install fontTools
def get_maoyan():
    #这个方法将页面内容和自定义字体拿下来
    maoyan_url = 'https://piaofang.maoyan.com/?ver=normal'
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36"
    }

    resp = requests.get(maoyan_url,headers=headers)
    html = resp.text
    result = re.search(r'charset=utf-8;base64,(.+?)\)',html)

    return html,result.group(1)

def analyst_font():
    html,font_face = get_maoyan()
    font_data = base64.b64decode(font_face)
    # with open('maoyan.ttf','wb') as fp:
    #     fp.write(font_data)
    base_Font = TTFont("maoyan.ttf")
    # base_Font.saveXML("maoyan.xml")
    baseGlyf = base_Font['glyf']
    baseFontMap = {
        0:baseGlyf['uniF802'],
        1:baseGlyf['uniEFD9'],
        2:baseGlyf['uniE170'],
        3:baseGlyf['uniEFEB'],
        4:baseGlyf['uniE840'],
        5:baseGlyf['uniE2B4'],
        6:baseGlyf['uniF093'],
        7:baseGlyf['uniF476'],
        8:baseGlyf['uniF7D3'],
        9:baseGlyf['uniE617'],
        # '.':baseGlyf['x'],
    }

    font = TTFont(io.BytesIO(font_data))
    glyf = font['glyf']
    #获取code 和name的关系
    codeNameMap = font.getBestCmap()
    # print(codeNameMap){120: 'x', 57676: 'uniE14C', 58201: 'uniE359', 58550: 'uniE4B6', 58985: 'uniE669', 59167: 'uniE71F', 59297: 'uniE7A1', 59381: 'uniE7F5', 60150: 'uniEAF6', 61492: 'uniF034', 63493: 'uniF805'} 十进制
    for code,name in codeNameMap.items():
        codeStr = "&#" + str(hex(code)).replace("0","",1)+";"
        # print(name)
        #根据name取出形状
        currentShape = glyf[name]

        #已经提前设定好了 字体形状和文字的关系 
        #我们需要找到当前字体对应真正的文字  
        for number, shape in baseFontMap.items():
            if shape == currentShape:
                codeStr = "&#" + str(hex(code)).replace("0", "", 1) + ";"
                html = re.sub(codeStr, str(number), html)
        with open("maoyan1.html", 'w', encoding='utf-8') as fp:
            fp.write(html)



def main():
    # get_maoyan()
    analyst_font()

if __name__ == '__main__':
    main()